package com.yl.chainStore.control.user

import com.yl.chainStore.control.BaseCtrl
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.common.annotations.PermsCode
import com.yl.users.entity.CompanyDept
import com.yl.users.services.ICompanyDeptService
import com.yl.users.services.ISysCompanyService
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.*
import java.lang.Exception

/**
 * 分院管理
 */
@RestController
@RequestMapping("company/subCompany")
open class CompanySubCompanyController(
	private val iSysCompanyService: ISysCompanyService,
	private val iCompanyDeptService: ICompanyDeptService
) : BaseCtrl() {

	/**
	 * 获取所有分院
	 */
	@GetMapping("getSubCompanyList")
	@PermsCode("company:subCompany:list")
	@Transactional
	open fun getSubCompanyList():ResponseBody {
		return returnSuccess(iSysCompanyService.getSubCompanyList(getContext().companyId))
	}

	/**
	 * 添加分院
	 */
	@PostMapping("addSubCompany")
	@PermsCode("company:subCompany:add")
	@Transactional
	open fun addSubCompany(@RequestBody companyDept: CompanyDept):ResponseBody{
		iSysCompanyService.addSubCompany(companyDept)
		return returnSuccess()
	}

	/**
	 * 修改分院
	 */
	@PostMapping("updateSubCompany")
	@PermsCode("company:subCompany:update")
	@Transactional(rollbackFor = [Exception::class])
	open fun updateSubCompany(@RequestBody companyDept: CompanyDept):ResponseBody{
		companyDept.subCompany = 1
		val updateDept = iCompanyDeptService.updateDept(companyDept)
		if(updateDept.bodyIsError()){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return updateDept
	}

	/**
	 * 删除分院
	 */
	@PostMapping("delSubCompany/{id}")
	@PermsCode("company:subCompany:del")
	@Transactional
	open fun delSubCompany(@PathVariable id:Long):ResponseBody{
		iCompanyDeptService.delDept(id)
		return returnSuccess()
	}

	@GetMapping("getAllSubCompany")
	@Transactional
	open fun getAllSubCompany():ResponseBody{
		val subCompanyList = iSysCompanyService.getSubCompanyList(getContext().companyId)
		val res = mutableListOf<Map<String,Any>>()
		for(sub in subCompanyList){
			val map = mutableMapOf<String,Any>()
			map["id"] = sub.id
			map["name"] = sub.name
			res.add(map)
		}
		return returnSuccess(res)
	}


}
